<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(text, index) in suggestions"
      :key="index"
      @click="$emit('search', text)"
    >
      <div
        slot="title"
        v-html="heighLigh(text)"
      ></div>
    </van-cell>
  </div>
</template>

<script>
import { getSuggestions } from '@/api/search.js'

// lodash 支持按需加载，有利于打包结果优化
import { debounce } from 'lodash'

export default {
  name: 'searchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      suggestions: []
    }
  },
  watch: {
    searchText: {
      handler: debounce(function (val) {
        this.onLoadSuggestions(val)
      }, 200),
      // handler (val) {
      //   this.onLoadSuggestions(val)
      // },
      immediate: true
    }
  },
  methods: {
    async onLoadSuggestions (q) {
      try {
        const { data } = await getSuggestions(q)
        console.log(data)
        if (data.data.options[0] === null) {
          this.suggestions = []
        } else {
          this.suggestions = data.data.options
        }
      } catch (err) {
        this.$toast('失败稍后重试')
      }
    },
    heighLigh (text) {
      const heighLighStr = `<span class="active">${this.searchText}</span>`
      // 正则表达式构造函数
      // 如果想要全文替换，使用正则表达式
      // g 全局
      // i 忽略大小写
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, heighLighStr)
    }
  }
}
</script>

<style scoped lang="less">
.search-suggestion {
  /deep/ .active {
    color: #2792ff;
  }
}
</style>
